<?php

namespace App\Http\Controllers\V1\API;

use App\Http\Controllers\V1\API\BaseController;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use Log;
class ImageUploadController extends BaseController
{
    //
    public function uploadTrainingsImage(Request $request) {
        // 自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
            'data' => [
                'pic_path' => '',
            ],
        );
        if ($request->method() === 'POST') {
            // 存储路径
            $storagePath = 'trainings';
            // 获取request中上传文件对象
            $image_file = $request->file('imageFile');
            if (empty($image_file) || !isset($image_file)) {
                $result = [
                    'errorCode' => Response::HTTP_NOT_FOUND,
                    'errorMsg' => '文件不存在',
                ];
                return $this->sendResponse($result, $result['errorCode']);
            }
            // 验证request中上传的文件类型
            $isValid = $this->validFile($image_file);
            if ($isValid == false) {
                $result['errorCode'] = Response::HTTP_BAD_REQUEST;
                $result['errorMsg'] = '图片文件[' . $image_file->getClientOriginalName() . '],文件格式不正确！';
            } else {
                // 在指定目录保存图片（原图）
                $originPath = Storage::disk('public')->put($storagePath, $image_file);

                // 检查文件是否上传成功
                $success = $this->checkFile($originPath);
                if ($success) {
                    $result['errorCode'] = Response::HTTP_OK;
                    $result['errorMsg'] = Response::$statusTexts[Response::HTTP_OK];
                    $result['data'] = array(
                        'picPath' => asset('storage' . '/' . $originPath),
                    );
                } else {
                    $result['errorCode'] = Response::HTTP_BAD_REQUEST;
                    $result['errorMsg'] = '上传失败！';
                }
            }
        }
        return $this->sendResponse($result, $result['errorCode']);
    }

    ///////////////////////////////////////////////////////////////////
    /// 功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 验证文件是否上传成功
     *
     * @param $url
     * @return bool
     */
    protected function checkFile($url)
    {
        // 验证文件已存在
        $exists = Storage::disk('public')->exists($url);
        if ($exists) {
            return true;
        }
        return false;
    }
    /**
     * 验证文件类型是否合法
     *
     * @param $objFile 文件对象
     * @return bool
     */
    protected function validFile($objFile)
    {
        // 合法文件类型
        $fileTypes = array('png', 'jpg', 'jpeg');
        if (in_array($objFile->getClientOriginalExtension(), $fileTypes)) {
            return true;
        }
        return false;
    }
}
